package com.example.controller;

import com.example.common.Result;
import com.example.entity.Goods;
import com.example.exception.CustomerException;
import com.example.service.GoodsService;
import com.example.vo.PriceVO;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Resource
    private GoodsService goodsService;

    @PostMapping("/add")
    public Result add(@RequestBody Goods goods) {
        goodsService.add(goods);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        goodsService.deleteById(id);
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Goods goods) {
        goodsService.updateById(goods);
        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Goods> goodsList = goodsService.selectAll();
        return Result.success(goodsList);
    }

    @GetMapping("/select/{id}")
    public Result select(@PathVariable Integer id) {
        Goods goods = goodsService.selectById(id);
        return Result.success(goods);
    }

    /**
     * 分页查询
     * pageNum: 当前的页码
     * pageSize: 每页的个数
     */
    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize){
        PageInfo<Goods> pageInfo = goodsService.selectPage(pageNum, pageSize);
        return Result.success(pageInfo);
    }

    @PostMapping("/getPrice")
    public Result getPrice(@RequestParam Double weight, @RequestParam Integer shippingBookId, @RequestParam Integer deliveryBookId) {
        PriceVO price;
        try {
            price = goodsService.getPrice(weight,shippingBookId,deliveryBookId);
        }catch (Exception e){
            throw new CustomerException("计算价格失败");
        }
        return Result.success(price);
    }
}
